package com.changgou.canal.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.common.vo.Result;
import com.changgou.content.feign.ContentFeign;
import com.changgou.content.pojo.Content;
import com.xpand.starter.canal.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

@CanalEventListener
public class ContentDataEventListener {

    @Autowired
    private ContentFeign contentFeign;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 自定义监听
     * destination 安装canal的时候指定名字；一般是example
     * schema 数据库
     * table 表
     * eventType 事件类型；新增、修改、删除
     * @param eventType 事件类型；新增、修改、删除
     * @param rowData 行数据
     */
    @ListenPoint(destination = "example", schema = "changgou_content", table = {"tb_content"},
            eventType = {CanalEntry.EventType.UPDATE, CanalEntry.EventType.INSERT, CanalEntry.EventType.DELETE})
    public void onEvent4(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        switch (eventType){
            case INSERT:
                refreshContentInRedis(rowData.getAfterColumnsList());
                break;
            case UPDATE:
                //修改之前
                refreshContentInRedis(rowData.getBeforeColumnsList());
                //修改之后
                refreshContentInRedis(rowData.getAfterColumnsList());
                break;
            default:
                //删除
                refreshContentInRedis(rowData.getBeforeColumnsList());
        }
    }

    /**
     * 实现更新redis中的缓存数据
     * @param columnsList 更新的那一行数据
     */
    private void refreshContentInRedis(List<CanalEntry.Column> columnsList) {
        //1、分类id的值
        String categoryId = getColumeValue(columnsList, "category_id");
        //2、根据分类id查询分类对应的内容列表
        Result<List<Content>> result = contentFeign.findByCategoryId(Long.parseLong(categoryId));
        List<Content> contentList = result.getData();
        //3、更新redis中分类的缓存
        stringRedisTemplate.boundValueOps("content_" + categoryId).set(JSON.toJSONString(contentList));
    }

    /**
     * 获取修改的那一行某一列的列值
     * @param columnsList 一行数据（有很多列）
     * @param columnName 列名
     * @return 列值
     */
    private String getColumeValue(List<CanalEntry.Column> columnsList, String columnName) {
        if (columnsList != null && columnsList.size() > 0) {
            for (CanalEntry.Column column : columnsList) {
                if (columnName.equals(column.getName())) {
                    return column.getValue();
                }
            }
        }
        return null;
    }
}
